import Axios, { Method } from 'axios'
import { ref } from 'vue'
const axios: any = Axios.create({
  timeout: 30000, // 请求超时时间 30s
})
const baseURL = import.meta.env.MODE !== 'development' ? '/dist/data' : 'https://gitee.com/api/v5/repos/lwj-wing/wings-nav/contents/'
const minUrl = `${baseURL}/dist/data/main.json`


const utf8Decoder = new TextDecoder('utf-8')

interface childrenType {
  link: string
  title: string
  introduction: string
  [p: string]: any
}
interface boxType {
  title: string
  docPath: string
  children: childrenType[]
  [p: string]: any
}
export default function install(): any {
  const fullData = ref<boxType[]>([])

  // 定义回调函数来处理返回的数据
  function handleData(data: any) {
    console.log('收到的数据:', data);
    // 在这里可以对返回的数据进行处理
  }

  // 发起JSONP请求
  const script = document.createElement('script');
  script.src = 'https://example.com/data?callback=handleData';
  document.body.appendChild(script);
  axios.get(minUrl).then(({data: {content}}: any) => {
    const datas = utf8Decoder.decode(new Uint8Array([...atob(content)].map(char => char.charCodeAt(0))))
    const  { boxList = [], editLink = { pattern: '' }}: any = datas
    console.log('data', datas, boxList)
    
    const data = boxList.map((item: any) => {
      const docName = typeof item === 'string' ? item : item.title
      return axios.get(`${baseURL}/${docName}.json`)
    })
    
    Promise.all(data).then((childrenList: any) => {
      fullData.value = boxList.map((item: any, index: number): boxType => {
        if(typeof item === 'string') {
          return {
            title: item,
            docPath: editLink.pattern.replace(':path', `${item}.json`),
            children: childrenList[index].data
          }
        }
        return {
          ...item,
          docPath: editLink.pattern.replace(':path', `${item}.json`),
          children: childrenList[index].data
        }
      })
    })
  })
  return {
    fullData
  }
}


